package com.redside.dao.spring;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.redside.dao.exception.DataException;
import com.redside.model.list.OptionsBean;

/**
 * @author - Peter Chapman
 * 
 */
public abstract class JdbcGenericListService extends BaseDaoSpring {

    private static final OptionsBean DEFAULT_OPTION = new OptionsBean();

    public JdbcGenericListService() {
        super();
    }

    /**
     * @throws DataException
     */
    @SuppressWarnings("unchecked")
    public List<OptionsBean> getList(String sql, Boolean includeEmpty) throws DataException {
        List<OptionsBean> results;
        try {
            ResultSetHandler beanHandler = new BeanListHandler(OptionsBean.class);
            QueryRunner qr = new QueryRunner(this.getDataSource());
            results = (List<OptionsBean>) qr.query(sql, beanHandler);
            if ((includeEmpty.booleanValue()) && (results != null)) {
                results.add(0, DEFAULT_OPTION);
            }
        } catch (Exception ex) {
            throw new DataException("Failure while getting list: " + ex.getMessage()
                    + " SQL: " + sql);
        }

        return results;
    }

}
